/**
 * 1004. 最大连续1的个数 III
 */
class Solution3 {
    public int longestOnes(int[] nums, int k) {
        int left = 0, right = 0, n = nums.length, ret = Integer.MIN_VALUE, count = 0;

        while(right < n) {
            if(nums[right] == 1 || count < k) {
                // 进窗口
                ret = Math.max(ret, right - left + 1);
                if(nums[right] == 0) count++;
                right++;
            } else {
                // 出窗口
                if(nums[left] == 0) count--;
                left++;
            }
        }

        return ret == Integer.MIN_VALUE ? 0 : ret;
    }
}